package gr.handmademarket.bl.operations;

import gr.handmademarket.hibernate.HibernateUtil;
import gr.handmademarket.po.implementations.Buyer;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * operation that saves a buyer.
 */
public class RegisterBuyerOperation {

	/**
	 * the buyer.
	 */
	private Buyer buyer;
	
	/**
	 * sellerHql
	 */
	@SuppressWarnings("nls")
	private static final String sellerHql = " select username from Seller where username=:username ";
	
	/**
	 * buyerHql
	 */
	@SuppressWarnings("nls")
	private static final String buyerHql = " select username from Buyer where username=:username ";
	
	/**
	 * Creates a new RegisterBuyerOperation object. 
	 *
	 */
	public RegisterBuyerOperation() {
		// empty
	}
	
	/**
	 * execution method.
	 */
	public void execute(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query sellerQuery = session.createQuery(sellerHql);
        executeQuery(sellerQuery);
        Query buyerQuery = session.createQuery(buyerHql);
        executeQuery(buyerQuery);
        session.save(buyer);
        session.getTransaction().commit();
	}
	
	/**
	 * @param query
	 */
	@SuppressWarnings("nls")
	private void executeQuery(Query query){
		query.setString("username", buyer.getUsername());
		if (query.list() != null && query.list().size() > 0){
        	throw new RuntimeException("user account already exists !");
        }
	}

	/**
	 * @return buyer.
	 */
	public Buyer getBuyer() {
		return buyer;
	}

	/**
	 * @param buyer
	 */
	public void setBuyer(Buyer buyer) {
		this.buyer = buyer;
	}
	
}
